package com.sndscl.rpc.common.util;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Description
 * @Author lsh
 * @Date 2020/10/14 10:50
 **/
public class ZookeeperClient {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper = null;

    public  void connection(String zkurl) throws IOException {
         zooKeeper = new ZooKeeper(zkurl, 10000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.getPath() + "\t" + watchedEvent.getState() + "\t" + watchedEvent.getType());
                countDownLatch.countDown();
            }
        });
        System.out.println(zooKeeper.getState());
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public  void createNode(String path,String data,CreateMode createMode) throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists(path,true);
        if(stat == null){
            //创建子节点
            zooKeeper.create(path,data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
        };
    }

    public  List<String> getChildren(String path) throws KeeperException, InterruptedException {
        //获取子节点
        return  zooKeeper.getChildren(path, true);
    }

    public  List<String> weatherDir(String path,Watcher watcher) throws KeeperException, InterruptedException {
        return zooKeeper.getChildren(path,watcher);
    }

    public  byte[] getData(String path) throws KeeperException, InterruptedException {
        return zooKeeper.getData(path,true,null);
    }
}
